/**
 * Copyright (c) 2010 icer He <icerhe@gmail.com>
 */
package com.icerhe.trigger.task;

import java.util.Timer;
import java.util.TimerTask;

import com.icerhe.trigger.R;
import com.icerhe.trigger.TaskHelper;

import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * @author icer
 *
 */
public class WifiDialog extends Activity {
	
	WifiTask task = null;
	int wait = 30; //等待30秒
	
	TextView message;
	
	Timer timer = new Timer();
	TimerTask timerTask = new TimerTask() {
		public void run() {
			Message msg = new Message();
			handler.sendMessage(msg);
		}
	};
	
	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			Resources res = getResources();
			if (--wait>=0) {
				CharSequence op = task.getWifiState()==WifiTask.ON?
					getText(R.string.wifi_on):getText(R.string.wifi_off);
				String text = String.format(res.getString(R.string.wifi_notice), wait, op);
				message.setText(text);
			} else {
				acceptWifiState();
				timer.cancel();
			}
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		//触发的task
		task = (WifiTask)TaskHelper.getCronTaskById(this, 
				getIntent().getIntExtra(CronTask.INTENT_TASK_ID, 0));
		
		showLayout();
		timer.schedule(timerTask, 500,1000);
	}
	
	private void showLayout() {
		LayoutInflater inflater = LayoutInflater.from(this);
		setContentView(inflater.inflate(R.layout.wifi_dialog, null));
		
		TextView title = (TextView)findViewById(R.id.WifiTaskTitle);
		TextView desc = (TextView)findViewById(R.id.WifiTaskDesc);
		message = (TextView)findViewById(R.id.WifiMessage);
		title.setText(task.title);
		desc.setText(task.description);
		
		Button accept = (Button)findViewById(R.id.accept);
		accept.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				acceptWifiState();
			}
		});
		
		findViewById(R.id.cancel).setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		
	}

	/**
	 * 进入/退出飞行模式
	 */
	private void acceptWifiState() {
		timer.cancel();
		task.acceptWifiState(WifiDialog.this);
		finish();
	}

}
